/**
 * canvas文字可换行（含\n）
 * @param {*} params 
 * @param {*} _canvas
 */
function textCanvas(params, _canvas) {

    // const image = new Image();
    // image.src=''
    //创建画布
    var canvas = _canvas||document.createElement('canvas');
    //设置画布大小
    canvas.width = params.width;
    canvas.height = params.height;
    // image.onload = () => {
    // ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
    // }

    canvas.style.letterSpacing = '5px';// 字符间距设置
    var ctx = canvas.getContext("2d");
    //字体属性
    ctx.font = params.font || '16px 微软雅黑';
    ctx.fillStyle = "white";
    ctx.textBaseline = "top";
    ctx.textAlign = "left";
    // ctx.fillText
    ctx.wrapText(params.text, params.x, params.y, params.text_w, params.lineheight || 20);//x,y,width,lineHeight

    return canvas;
}

/**
 * 可换行扩展
 * https://www.zhangxinxu.com/wordpress/2018/02/canvas-text-break-line-letter-spacing-vertical/
 * @param {*} text 
 * @param {*} x 
 * @param {*} y 
 * @param {*} maxWidth 
 * @param {*} lineHeight 
 */
CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) {
    if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
        return;
    }

    var context = this;
    var canvas = context.canvas;

    if (typeof maxWidth == 'undefined') {
        maxWidth = (canvas && canvas.width) || 300;
    }
    if (typeof lineHeight == 'undefined') {
        lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) || parseInt(window.getComputedStyle(document.body).lineHeight);
    }

    // 字符分隔为数组
    var arrText = text.split('');
    var line = '';

    for (var n = 0; n < arrText.length; n++) {
        var testLine = line + arrText[n];
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0 || arrText[n] == '\n') {
            context.fillText(line, x, y);
            line = arrText[n];
            y += lineHeight;
        } else {
            line = testLine;
        }
    }
    context.fillText(line, x, y);
};



// base64转blob
function base64ToBlob(urlData) {
    var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1].replace(/\s|\n/g, "")), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

// 前端保存图片
function onDownCanvas(canvas, filename) {
    var filetype = filename.split('.')[1];
    var base64 = canvas.toDataURL(filetype=="png"?"image/png":"image/jpeg", 0.9);
    var a = document.createElement("a");
    a.download = filename;
    a.href = base64;
    document.body.appendChild(a);
    a.click();
    a.remove();
}
// 后端fs保存图片文件
function saveImg(canvas, _path) {
    var filetype = filename.split('.')[1];
    var base64 = canvas.toDataURL(filetype=="png"?"image/png":"image/jpeg", 0.9);
    var url = base64.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = new Buffer(url, 'base64');
    fs.writeFile(_path, dataBuffer, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log('success');
        }
    });
}